#!/bin/bash -e

echo "Capturing video from $1 with resolution $2x$3 and format $4"

v4l2-ctl -d $1 \
    --set-fmt-video=width=$2,height=$3,pixelformat=$4 \
    --stream-mmap=3 \
    --stream-skip=3 \
    --stream-to=output.$5 \
    --stream-count=1 \
    --stream-poll

FILE=output.$5

case ${FILE##*.} in
    yuv)
        ffmpeg -s $2x$3 -pix_fmt yuyv422 -i output.$5 output.png -y
        ffmpeg -s $2x$3 -pix_fmt yuyv422 -i output.$5 output.jpg -y
        ;;
    mp4|avi)
        ffmpeg -i "$FILE" output.jpg
        ;;
esac